package com.strongbj.iot.devices.dam.response.handle.v1;

import java.util.ArrayList;
import java.util.List;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import io.netty.channel.ChannelHandlerContext;

import com.alibaba.fastjson.JSON;
import com.strongbj.core.util.ByteUtil;
import com.strongbj.core.util.ContextUtils;
import com.strongbj.iot.devices.dam.message.DAMMessage;
import com.strongbj.iot.devices.dam.message.MQMessageOfDAM;
import com.strongbj.iot.devices.dam.response.entity.CabinetEntity;
import com.strongbj.iot.devices.dam.response.entity.SensorOfAwsPostdataEntity;
import com.strongbj.iot.devices.dam.response.entity.SensorParamesEntity;
import com.strongbj.iot.mq.producer.TopicSender;

/**
 * 开关门状态的处理
 * @author yuzhantao
 *
 */
public class DoorStateHandle extends DAMV1Handle{
	private static Logger logger = LogManager.getLogger(DoorStateHandle.class.getName());
	private TopicSender topicSender = (TopicSender) ContextUtils.getBean("topicSender");
	private static final String TOPIC="damRealTimeInfoToService";
	private static final String ACTION_CODE = "realTimeDatas";
	private static final String DEV_TYPE="damDc";
	private byte prevDoorState=0;									// 门开关状态，0为关门，1为开门
	
	@Override
	protected boolean isHandleDAMMessage(DAMMessage t) {
		if(t.getCommand()==0x31){
			return true;
		}else{
			return false;
		}
	}

	@Override
	public Object handle(ChannelHandlerContext ctx, DAMMessage t) {
		CabinetEntity cabinet = new CabinetEntity();
		cabinet.setDoorState(t.getDatas()[0]);  // 0为关门；1为开门
		
		/**
		 * 由于硬件采用磁开关，机柜是铁质的原因，在门晃动时开关会发送多次开门信号，顾下面代码过滤多次的开门信号。
		 */
		if(this.prevDoorState==cabinet.getDoorState()) {
			logger.debug("DAM设备 过滤和上次相同的门状态信息  机柜编号={}	 doorState={}", t.getAddressCode(), this.prevDoorState);
			return null;
		}
		this.prevDoorState=cabinet.getDoorState();
		
		List<SensorParamesEntity> sensorList = new ArrayList<>();
		SensorParamesEntity spe = new SensorParamesEntity();
		spe.setSensorPosition(0);
		spe.setSensorType(3);
		spe.setSensorDatas(t.getDatas()[0]);
		sensorList.add(spe);
		
		MQMessageOfDAM msg = new MQMessageOfDAM();
		msg.setDevType(DEV_TYPE);
		msg.setActioncode(ACTION_CODE);
		msg.setTimestamp(ByteUtil.bytesToLong(t.getSn()));
		SensorOfAwsPostdataEntity sensorOfAwsPostdataEntity=new SensorOfAwsPostdataEntity();
		sensorOfAwsPostdataEntity.setSensorList(sensorList);
		sensorOfAwsPostdataEntity.setRackConverCode(ByteUtil.byteArrToHexString(t.getAddressCode()));
		msg.setAwsPostdata(sensorOfAwsPostdataEntity);
		String json = JSON.toJSONString(msg);
		topicSender.send(TOPIC, json);
		logger.info("DAM设备 向MQ发送机柜门数据	 JSON={}",json);
		
		sensorList.clear();
		sensorList=null;
		sensorOfAwsPostdataEntity.setSensorList(null);
		sensorOfAwsPostdataEntity=null;
		msg.setAwsPostdata(null);
		msg=null;
		return null;
	}
}
